<?php

/**
 * Created by PhpStorm.
 * User: dev
 * Date: 17/11/14
 * Time: 3:18 PM
 */
class Member_Post_Edit_Controller extends Base_Controller
{

	public $restful = true;
	public $post_data = array();
	public $location_data = array();
	public $category_data = array();

	public $POSTID;
	public $USER;


	public function __construct()
	{
		parent::__construct();
		//--Your Code --//
		$this->theme->set_theme("default");
		$this->theme->set_layout("member");

		$this->POSTID = 0;
		$this->USER = Auth::user();
	}


	public function get_edit($post_id, $step = 1)
	{
		$post = Post::find($post_id);
		$data['post'] = $post;
		$this->POSTID = $post_id;
		/*-- BREADCRUMB */
		Breadcrumb::addbreadcrumb('Home', URL::base());
		Breadcrumb::addbreadcrumb(' Member', URL::base() . '/member');
		Breadcrumb::addbreadcrumb('Edit Business', URL::base());
		Breadcrumb::setSeparator('&raquo;');
		$data['breadcrumb'] = Breadcrumb::generate();


		switch ($step) {

			case 1:

				/*-- GET CATEGORIES FROM TERMS TABLE --*/
				$pre_cats = Terms::category($this->POSTID, false, 'ASC');
				$data['pre_cats'] = $pre_cats;



				$k = Terms::keywords($post_id);
				$data['keywords'] = $k;

				$data['title'] = "Edit : " . $post->title . " : Step: 1";
				$data['cat_parent'] = Categories::parent(0);
				$data['location'] = Locations::find(Terms::location($post_id, $last = true));
				$data['category'] = Categories::find(Terms::category($post_id, $last = true));
				return $this->theme->render('member::post.edit1', $data);
				break;

			case 2;

			$data['post'] = Post::where('id','=',$post_id)->first();
			$data['title'] = "Edit : " . $post->title . " : Step: 2";
			$data['cat_parent'] = Categories::parent(0);
			$data['location'] = Locations::find(Terms::location($post_id, $last = true));
			$data['category'] = Categories::find(Terms::category($post_id, $last = true));
			return $this->theme->render('member::post.edit2', $data);
			break;
				
			case 3;
				
			$data['post'] = Post::where('id','=',$post_id)->first();

			$post = $data['post'];
			$term_loc = Terms::location($post_id, false);
			$l ='';
			foreach($term_loc as $tl){
				$l .= Locations::find($tl->value)->name.',';
			}
			$post = Post::find($post_id);
			$address1 = $post->address1;
			$address2 = ($post->address2 != '' ? ', '.$post->address2 : '');
			$l = $address1.$address2.','.$l;
			
			
			
			
			
			
			
			
			$config = array();
			$config['locationview'] = $l;
			$long_lat = $post->lat.','.$post->long;
				
			$config['minifyJS'] = TRUE;
			$config['map_type'] = 'ROADMAP';
			$config['trafficOverlay'] = 'TRUE';
			$config['map_height'] = '300px';
			$config['zoom'] = "13";
			$config['center'] = $long_lat;
				
			$config['adsense'] = FALSE;
			$config['adsensePublisherID'] = Settings::get('en','adsense_pub_id');
			$config['adsenseFormat'] = 'HALF_BANNER';
			$config['adsensePosition'] = 'BOTTOM_LEFT';
				
			$data['locationview'] = $config['locationview'];
			$Gmap = new Gmaps();
			$Gmap->initialize($config);
			$marker = array();
			$marker['draggable'] = true;
			$marker['ondrag'] = 'document.getElementById("lat").value=   + event.latLng.lat()  ; document.getElementById("long").value=   + event.latLng.lng()  ; ' ;
				
			$marker['icon'] = \Laravel\URL::base()."/public/pointer1.png";
			$marker['position'] = $long_lat;
			$marker['infowindow_content'] = "<strong>".$post->title."</strong>"."</br>".$post->address1;
			$marker['animation'] = 'DROP';
			$Gmap->add_marker($marker);
				
			$data['map'] = $Gmap->create_map();
				
			
				
			$data['title'] = "Edit : " . $post->title . " : Step: 3";
			$data['cat_parent'] = Categories::parent(0);
			$data['location'] = Locations::find(Terms::location($post_id, $last = true));
			$data['category'] = Categories::find(Terms::category($post_id, $last = true));
			return $this->theme->render('member::post.edit3', $data);
			break;

		}
	}

	public function post_edit($post_id, $step = 1)
	{
		$this->POSTID = $post_id;

		switch ($step) {
			case 1:

				$rules = array(
				'title' => 'required|min:5',
				'category' => 'required',
				//'keywords' => 'required',
				'street' => 'required',
				//'selectbox-mylocation' => 'required',
				'location' => 'required',
				);

				$validator = Validator::make(Input::get(), $rules);

				if ($validator->fails()) {
					return Redirect::back()->with_input()->with_errors($validator)->with('message', 'Invalid Operation !');
				} else {
					$this->post_data = array(
							'title' => Input::get('title'),
							'address1' => Input::get('street'),
							'address2' => Input::get('address2'),
							'zip_code' => Input::get('zip'),
							'updated_at' => Commoncall::current_timestamp(),
					);

					// Prepare Category
					$cat = Hierarchy::get_ancestors('categories', Input::get('category'));
					$cat_array = array();
					foreach ($cat as $c) {
						$cat_array[] = $c->id;
					}
					$this->category_data = $cat_array;

					// Prepare Location
					$loc = Hierarchy::get_ancestors('locations', Input::get('selectbox-mylocation'));
					if (!$loc) {
						$loc = Hierarchy::get_ancestors('locations', Input::get('location'));
					}

					$loc_array = array();
					foreach ($loc as $l) {
						$loc_array[] = $l->id;
					}
					$this->location_data = $loc_array;

					/*--UPDATE POST --*/
					DB::table('post')
					->where('id', '=', $post_id)
					->update($this->post_data);


					/*--INSERT TERM (CATEGORY) - DELETE BEFORE --*/
					$sql = "delete from terms where post_id = $post_id and term = 'category'";
					DB::query($sql);

					foreach ($this->category_data as $cat) {
						$key_data = array(
								'post_id' => $this->POSTID,
								'term' => 'category',
								'caption' => 'Category',
								'value' => $cat
						);
						DB::table('terms')->insert($key_data);
					}

					/*--INSERT TERM (KEYWORD) --*/
					$ka = Input::get('keywords');
					if ($ka) {
						$sql = "delete from terms where post_id = $post_id and term = 'keyword'";
						DB::query($sql);

						foreach ($ka as $value) {
							$key_data = array(
									'post_id' => $this->POSTID,
									'term' => 'keyword',
									'caption' => 'Keyword',
									'value' => $value
							);
							DB::table('terms')->insert($key_data);
						}
					}


					/*--INSERT TERM (LOCATION) - DELETE BEFORE --*/
					$sql = "delete from terms where post_id = $post_id and term = 'location'";
					//dd($sql);
					DB::query($sql);

					foreach ($this->location_data as $loc) {
						$loc_data = array(
								'post_id' => $this->POSTID,
								'term' => 'location',
								'caption' => 'Location',
								'value' => $loc
						);

						DB::table('terms')->insert($loc_data);
					}

				}
				/* $title = Input::get('title');
				 $category = Input::get('category');
				$search_category = Input::get('search_category');
				$street = Input::get('street');
				$address2 = Input::get('address2');
				$location = Input::get('location');
				$mylocation = Input::get('selectbox-mylocation');

				if (isset($search_category) && $search_category == '') {
				$category = $category;
				} else {
				$category = $search_category;
				}

				if (isset($mylocation) && $mylocation == '') {
				$location = $location;
				} else {
				$location = $mylocation;
				}

				$step1 = array(
						'post_id' => $post_id,
						'title' => $title,
						'category' => $category,
						'address1' => $street,
						'address2' => $address2,
						'location' => $location,
				);

				Session::put('step1', $step1);*/
				return Redirect::to("/member/post/edit/$post_id/2");
				break;
			case 2:

				$rules = array(

				'phone1' => 'required',
				'email' => 'required|email',
				'website' => 'url|active_url',
				'description' => 'required',


				);
				$validator = Validator::make(Input::get(), $rules);
				if( $validator->fails() )
				{
					return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
				}
				else
				{
					$filename = Input::file('image.name');
					if($filename == TRUE){
							

						$extension = File::extension($filename);
						$image = Input::file('image');
						$dirPath = path('storage').'uploads/logos/';
						$filename = $image['name'];

						//	if($filename == FALSE){
						//	$filename = 'no-logo.jpg';
						//	}

						$createFolders = true;
						$backgroundColor = null;
						$imageQuality = 100;

						//--NEW NAME --//
						$filename = md5($filename).'.'.$extension;

						$layer = PHPImageWorkshop\ImageWorkshop::initFromPath($image['tmp_name']);

						$thumbWidth = 300; // px
						$thumbHeight = 250;
						$conserveProportion = false;
						$positionX = 0; // px
						$positionY = 0; // px
						$position = 'LT';

						$layer->resizeInPixel($thumbWidth, $thumbHeight, $conserveProportion, $positionX, $positionY, $position);
						$layer->save($dirPath, $filename, $createFolders, $backgroundColor, $imageQuality);


					
							
						$post_data = array(
								'phone1'    => Input::get('phone1'),
								'phone2'    => Input::get('phone2'),
								'email'     => Input::get('email'),
								'website'    => Input::get('website'),
								'fax'       => Input::get('fax'),
								'tollfree'  => Input::get('tollfree'),

								'contact_name'  => Input::get('contact_name'),
								'contact_name2'  => Input::get('contact_name2'),
								'contact_no'  => Input::get('contact_no'),
								'contact_no2'  => Input::get('contact_no2'),

								'description'       => Input::get('description'),
								'services'  => Input::get('services'),
								'logo' => $filename,
						);
						
					
					}else{
						
							
						$post_data = array(
								'phone1'    => Input::get('phone1'),
								'phone2'    => Input::get('phone2'),
								'email'     => Input::get('email'),
								'website'    => Input::get('website'),
								'fax'       => Input::get('fax'),
								'tollfree'  => Input::get('tollfree'),
									
								'contact_name'  => Input::get('contact_name'),
								'contact_name2'  => Input::get('contact_name2'),
								'contact_no'  => Input::get('contact_no'),
								'contact_no2'  => Input::get('contact_no2'),
									
								'description'       => Input::get('description'),
								'services'  => Input::get('services'),
									
						);
					}
					DB::table('post')->where('id', '=',$post_id)
					->update($post_data);

				}

				return Redirect::to("/member/post/edit/$post_id/3");
				break;

			case 3:


				$rules = array(
				'lat' => 'required',
				'long' => 'required',
				);
				
				$validator = Validator::make(Input::get(), $rules);
				if( $validator->fails() )
				{
					return Redirect::back()->with_input()->with_errors($validator)->with('message','Invalid Operation !');
				}
				else
				{
				
					$post_data = array(
							
							'lat' => Input::get('lat'),
							'long' => Input::get('long')
							);
					
					DB::table('post')->where('id','=',$post_id)->update($post_data);
					
				}
				
				return Redirect::back();
				break;

		}


		/** CHECK DATA EXIST */
		/*$sql = "SELECT P.* from post P
		 INNER JOIN terms T1 on P.id = T1.post_id and (T1.term='category')
		and T1.value = $category
		INNER JOIN terms T2 on P.id = T2.post_id and (T2.term='location')
		and T2.value = $location
		and P.title =".'"'.$title.'"'."
		group by P.id limit 0,1;";

		$result = DB::query($sql);

		if($result){
		return Redirect::back()->with_input()->with('message','Already Exist!');
		}*/


		dd(Session::get('step1'));


	}
}